<?php

namespace App\Http\Middleware;

use Closure;

class apiDecryptMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //解密
        $array = $request->all();
        try {
            $data = apiDecrypt($array['data']);
        }catch (\Exception $e) {
            echo json_encode(config('errorCodes.apiDecrypt'),JSON_UNESCAPED_UNICODE);die;
        }
        //验证签名
        $signature = createSign($data['time'],$data['nonce']);
        if ($signature !== $array['sign']) {
            echo json_encode(config('errorCodes.apiSignError'),JSON_UNESCAPED_UNICODE);die;
        }
        //替换数据
        $request->replace($data);
        //删除数据
        $request->offsetUnset('time');
        $request->offsetUnset('nonce');
        return $next($request);
    }
}
